<?php
	require_once("include/common.php");

	$uid = $_GET['uid'] ?? '' ;
?>

<!DOCTYPE html>
<html lang="en" ng-app="deviceApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">

<title>用户数据列表</title>

	<?php
		require_once("pages/resources.php");
	?>
<!-- 
	<link href="/meter/resources/bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet">
	<link href="/meter/resources/bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet">	
-->
	<script src="/meter/resources/jquery/jquery-2.0.3.js"></script>
	<script src="/meter/resources/js/jquery.jeditable.lk.js"></script>
 	<script src="/meter/resources/angular-1.5.5/angular.js"></script>
 	<script src="/meter/resources/js-base-util.js"></script>


	<script src="/meter/resources/echarts-3.1.6/echarts.min.js"></script>
	<script src="/meter/resources/js/jquery.jeditable.lk.js"></script>
 	

 
</head>
<body class="sidebar-narrow"  id="deviceCtrl" ng-controller="deviceCtrl">

	<!-- Navbar -->
	 
	<?php
		require_once("pages/navbar.php");
	?>
	<!-- /navbar -->


	<div class="page-container sidebar-hidden">

		<!-- Sidebar -->
		 
		<?php
			require_once("pages/siderbar.php");
		?>
		<!-- /sidebar -->


		<!-- Begin: Content -->
		<div class="page-content">
			<!-- Page header -->
            <div class="page-header">
                <div class="datatable-header">
                	<div style="    margin-top:30px">
						 

	                	<div   style="display: table-cell; width: 10% ">
		                        <b>Date:</b> <select id="dateSelect" ng-model="date"  ng-change="changeDate();">
		                        	<option value="">All</option>
		                        	<option value="R">Raw</option>
		                        	<option value="Y">YEAR</option>
		                        	<option value="M">Month</option>
		                        	<option value="D">Day</option>
		                        	<option value="H">Hour</option>
		                        </select>
		                    </div>


						<div class="dataTables_length" id="DataTables_Table_0_length" style="width: 40%">
							 
							<div class="uploader" style="width: 80%">
								<input type="file" name="file" size="50" class="styled" onchange="uploadFiles();">
								<span class="filename" style="-webkit-user-select: none;">上传Excel文件</span>
								<span class="action" style="-webkit-user-select: none;">上传Excel文件</span>
							</div>
							<div style="float: right; padding-top:0.5em;">
							<a href="templates/template-user-data.xlsx">下载模板</a>
							</div>
						</div>
					</div>
				</div>

				 
          
            </div>
            <!-- /page header -->  
			 
	        <div>
	        	<div style="float: left; left: 0px; width: 58%">
					 
					<div style="float: right">

						<a href="#" ng-if="begin>0" ng-click="page(-1);">Previous</a>
						<span ng-if="begin==0" style="color: lightgrey">Previous</span>
						-
						<a href="#" ng-if="results.length==size" ng-click="page(1);">Next</a>
						<span ng-if="results.length<size" style="color: lightgrey">Next</span>
					</div>
					
	            	<table class="table table-striped table-bordered" >
						<thead>
							<tr>
								<td> 序号 </td>
								 
								<td> 用户  </td>
								<td> 类型  </td>
								<!-- <td> 开始  </td> -->
								<td> 结束  </td>
								<!-- <td> OFF  </td> -->
								<!-- <td> 数值1 </td> -->
								<td> 读数  </td>
								<td> 能耗(KWh)  </td>
								<td> 采集  </td>
								<td> 同步  </td> 
						    </tr>
						</thead>
						<tbody>

							<tr ng-repeat="dev in results">
								<td>{{dev._ID}}</td>
					    		<td>
					    			<a href="?uid={{dev._DEVID}}">
					    			{{dev._DEVID}}
					    			</a>
					    		</td>
					    		<td> <a href="#" ng-click="changeDate(dev._DATE)" >{{dev._DATE}}</a></td>  
					    		<!-- <td>{{dev._START}}</td>  -->
					    		<td>{{dev._END}}</td>
					    		<!-- <td>{{(dev._OFF/(60)).toFixed(0)}}</td>  -->
					    		<!-- <td>{{dev._PREVIOUS}}</td>   -->
					    		<td>{{dev._LAST}}</td> 
					    		<td>{{dev._VALUE}}</td>
					    		<td>{{dev._TIMESTAMP}}</td>
					    		<td>{{dev._FLAG ? 'YES' : 'NO'}}</td> 
					    	</tr>
						</tbody>					
					</table>


					<div style="float: left">
						Size : <span>{{results.length}}</span>
					</div>
					<div style="float: right">

						<a href="#" ng-if="begin>0" ng-click="page(-1);">Previous</a>
						<span ng-if="begin==0" style="color: lightgrey">Previous</span>
						-
						<a href="#" ng-if="results.length==size" ng-click="page(1);">Next</a>
						<span ng-if="results.length<size" style="color: lightgrey">Next</span>
					</div>


				</div>
				<div>
					<div id="chartSerial" style="float: right; right: 10px; height: 800px; width:38%;border: 1px"></div>
				</div>
			</div> 
		</div>
		<!-- End: Content -->

 


	</div>

	<div style="position: fixed; bottom: 0px ; right: 0px; z-index: 999">
             
        <span id="responseId" class="label ">
            success!
        </span>
      
    </div>

</body>
<script type="text/javascript">

	var users =  null;

	function response_status( command , result ){
		if(result.status == 0 ){
			$('#responseId').removeClass('label-warning');
			$('#responseId').addClass('label-success');
			$('#responseId').text( 'success! ' + command);
		}else {
			$('#responseId').removeClass('label-success');
			$('#responseId').addClass('label-warning');
			
			$('#responseId').text( 'Error : ' + result.status + ' ' + result.message + '\n' + command );
		}
	}
	
 
    var app = angular.module('deviceApp', []);
    app.controller('deviceCtrl', 
    	function($scope, $http, $timeout) {
        	$scope.user = '<?=$uid?>' ;
     		$scope.date = null ;
     		$scope.begin = 0 ;
     		$scope.size  = 100 ;

            $scope.results = [] ;
         	$scope.chart  = null ;
    
 			$scope.resize = function(){
 				if( $scope.chart ){
 					$scope.chart .resize();
 				}
 			}
	  		
         	$scope.change= function(){
              	$scope.loadData();
            }  
            $scope.changeDate= function(date ){
            	if( date )
 					$scope.date = date;


              	$scope.loadData();
            } 

 			$scope.selectAll= function(){
 				$scope.user = null;


              	$scope.loadData();
            } 
		 	$scope.page= function( dir ){
        		if(dir>0){
        			if( $scope.results.length == $scope.size)
        				$scope.begin += $scope.size;	
        			else
        				return ;

        		}else {

        			$scope.begin -=$scope.size;
        			if( $scope.begin <0 )
        				$scope.begin = 0;
        		}
        		

              	$scope.loadData();
            }  


            $scope.loadData = function() {
                
              
                var url = '/meter/rest/disp.php?m=userdata'  ;
   			 	url = _appendUrlList( url, "user" , $scope.user  );
   			 	url = _appendUrlList( url, "order" , '-_TIMESTAMP'  );
   			 	url = _appendUrlList( url, "begin" , $scope.begin  );
   			 	url = _appendUrlList( url, "size" , $scope.size   );
   			 	 
   			 	url = _appendUrlList( url, "date" , $scope.date  );

                $http.get( url )
                    .success(
                        function(response) 
                        {

                            response_status( 'load meters data ... ' + $scope.meter , response );
                            if( response.status != 0 )
                            {  
                                return ;
                            }

                            response = JSON.retrocycle(response);

                           	$scope.results = response.result ;

 							if( $scope.chart  == null ){
                           	 	$scope.chart = new chartSerial( {
                                	container : 'chartSerial' 
                            	} ); 
                        	}

                        	$scope.chart.load( 
                                    {} , 
                                    response.result);
                        
                        

                        }
              );
            };   

                // init 
        
            $scope.loadData();
            
  
        });

    window.onresize = function(){
        var ctrl = angular.element('#deviceCtrl');
        var $scope= ctrl.scope();
        if( $scope )
            $scope.resize(  );
                 
    }

var kWhMWh = 'kWh' ;


function transferKM( value ){
	if(kWhMWh == 'kWh')
		return value;
	else
		transferMWh( value );
}



function transferMWh(value) {
	var val ;
	if(value!=undefined && value!='-' && value != null  ){
		value = value / 1000 ;
		val   =   value.toFixed(1) + '';
	}else {
		val   =  value + ' KWh';
	}
	return val;
} 

function chartSerial(opts){

 	this.opts = opts ;
	this.chart = null ;

	this.load = function ( opts , result){
	 	var that = this;
 	 	 
		processSerials(that, opts, result);
	 	return this;
	}

		 
 	this.error = function ( status , message  ){
	 	var that = this;
	 	_processChart ( that, null ,null ,{
	 		status:status,
	 		message :message
	 	} );
		return this;
	}
	 
	var processSerials =  function ( that , opts, result ){
	 
	
		var groups = {};
		
	 	for( var j = 0; j< result.length;j++){ 
			var obj = result[j];
			var tmobj = _parseDate(obj._END);
			var meter = obj._DEVID;

			var group = groups[meter];
			if( group == null ){
				group = {
					symbolSize: 8,
		          	hoverAnimation: true,
					name : meter,
					type : 'line',
					data :  []
				} ;

				groups[meter] = group;
			}

			group.data.push([ tmobj,obj._VALUE] ) ;
		}		
	 	
		var serials = [] ;

		for( group in groups){
			if(groups.hasOwnProperty(group)){
				serials.push( groups[group]);
			}
		}

		 
 	 
 	 	_processChart( that , opts, serials );
	} 



	this.getChart = function (){
		if( this.chart !=null )
			return this.chart;
	    this.chart = echarts.init(document.getElementById( this.opts.container  ), 
	    	this.opts.theme);
	  	return this.chart;
	    
	}

	 
	var _processChart = function ( that , opts, data , error ){

		var option = null;

		if( data && !error ) {
			option = {
				title: {
					x: 'left',
					text: '',
					subtext: kWhMWh,
					link: ''
				},
			    tooltip: {
			        trigger: 'axis',
			        formatter: function (params) {
			        	
			        	var value = '';
			        	if(params && params[0] && params[0].value )
			        		value = params[0].value[1];
			        	var val =  value + ' ' + kWhMWh + '<br/>';
			        	return  val;
			        	
			                 
			        },
			        axisPointer: {
			            animation: false
			        }
			    },
				toolbox: {
					show: true,
					 
				},
				dataZoom: {
					type: 'inside', // 在触摸屏上支持 双手操作
			        show: true,
			        start : 0
		  		},
				calculable: true ,
				grid: {
					borderWidth: 0,
					left: '3%',
					top :  '1%',
			        right: '1%',
			        bottom: '1%',
			        containLabel: true
				},
				yAxis: [
					{
						type: 'value',
						show: true,
						axisLabel: {
							formatter: function (value) {
								return transferKM(value);
			        		} 
						}
					}
				],		
				xAxis: [
					{
						type: 'time',
						show: true,
						axisLabel: {
							formatter: '{value} '
						}
					}
				],

				series:  data
			};
		}else {
			option = {
			    title : {
			        text:  'ErrorCode :' + error.status +'\n' + error.message   ,
			        x:'center'
			    },
			    
			};
		}
	 	var chart = that.getChart();
		chart.setOption ( option, true ); 
		chart.hideLoading(); 
	     
	 
	} 
	                 
	this.resize = function(){
		 this.chart  && this.chart.resize(); 
	}
}



function uploadFiles() {
   		var file = $('input[name="file"').get(0).files[0];
   		if( !file )
   			return ;
		var formData = new FormData();
		formData.append('file', file);

		var htmlv = $('#uploadDiv').html();
		$('#uploadDiv').html(htmlv);

		$.ajax({
		  url : '/meter/rest/disp.php?m=userdataupload',
		  type : 'POST',
		  data : formData,
		  cache : false,
		  contentType : false,
		  processData : false,
		  success : function( result , textStatus, jqXHR) {
		   // var result = JSON.parse(jqXHR.responseText);
		    // alert(userObj);
		    if(result.status == 0 ){
		    	 reloadData();
		    }else {
		    	alert( result.message );
		    }
		  },
		  error : function(jqXHR, textStatus, errorThrown) {
		    alert(textStatus);
		  }
		});
   }

    function reloadData(  ){
        var ctrl = angular.element('#deviceCtrl');
        var $scope= ctrl.scope();
 
        $scope.loadData();
    }
 

</script>
</html>
